#!/bin/sh

# This file is part of netfilter-persistent
# (was iptables-persistent)
# Copyright (C) 2009, Simon Richter <sjr@debian.org>
# Copyright (C) 2010, 2014 Jonathan Wiltshire <jmw@debian.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.

set -e

rc=0
done=0

TABLES="filter nat broute"

for i in $TABLES; do
	modprobe -q ebtable_$i
done

RULES=/etc/ebtables/rules

if [ -x ebtables ]; then
	echo "Warning: ebtables binary not available"
	exit
fi

load_rules()
{
	#load ebtables rules
	for i in $TABLES; do
		done=1
		if [ -f $RULES.$i ]; then
			ebtables -t $i --atomic-file $RULES.$i --atomic-commit
			if [ $? -ne 0 ]; then
				rc=1
			fi
		fi
	done
	if [ "x$done" = "x0" ]; then
		echo "Warning: skipping ebtables (no rules to load)"
	fi
}

save_rules()
{
	#save ebtables rules
	for i in $TABLES; do
		ebtables -t $i --atomic-file $RULES.$i --atomic-save
		# zero the counters
		ebtables -t $i --atomic-file $RULES.$i -Z
	done
}

flush_rules()
{
	for i in $TABLES; do
		ebtables -t $i --init-table
	done
}

case "$1" in
start|restart|reload|force-reload)
	load_rules
	;;
save)
	save_rules
	;;
stop)
	# Why? because if stop is used, the firewall gets flushed for a variable
	# amount of time during package upgrades, leaving the machine vulnerable
	# It's also not always desirable to flush during purge
	echo "Automatic flushing disabled, use \"flush\" instead of \"stop\""
	;;
flush)
	flush_rules
	;;
*)
    echo "Usage: $0 {start|restart|reload|force-reload|save|flush}" >&2
    exit 1
    ;;
esac

exit $rc

